
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_CN">
  <head>
    <meta charset="utf-8" />
    <title>collections --- 容器数据类型 &#8212; Python 3.7.8 文档</title>
    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <script type="text/javascript" src="../_static/translations.js"></script>
    
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    
    <link rel="search" type="application/opensearchdescription+xml"
          title="在 Python 3.7.8 文档 中搜索"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="关于这些文档" href="../about.html" />
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="copyright" title="版权所有" href="../copyright.html" />
    <link rel="next" title="collections.abc --- 容器的抽象基类" href="collections.abc.html" />
    <link rel="prev" title="calendar --- 日历相关函数" href="calendar.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/3/library/collections.html" />
    
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
    
    
    
    <style>
      @media only screen {
        table.full-width-table {
            width: 100%;
        }
      }
    </style>
 

  </head><body>
  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             accesskey="I">索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="collections.abc.html" title="collections.abc --- 容器的抽象基类"
             accesskey="N">下一页</a> |</li>
        <li class="right" >
          <a href="calendar.html" title="calendar --- 日历相关函数"
             accesskey="P">上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">3.7.8 Documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python 标准库</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">数据类型</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-collections">
<span id="collections-container-datatypes"></span><h1><a class="reference internal" href="#module-collections" title="collections: Container datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> --- 容器数据类型<a class="headerlink" href="#module-collections" title="永久链接至标题">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.7/Lib/collections/__init__.py">Lib/collections/__init__.py</a></p>
<hr class="docutils" />
<p>这个模块实现了特定目标的容器，以提供Python标准内建容器  <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> , <a class="reference internal" href="stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a> , <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> , 和 <a class="reference internal" href="stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> 的替代选择。</p>
<table class="docutils align-default">
<colgroup>
<col style="width: 24%" />
<col style="width: 76%" />
</colgroup>
<tbody>
<tr class="row-odd"><td><p><a class="reference internal" href="#collections.namedtuple" title="collections.namedtuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">namedtuple()</span></code></a></p></td>
<td><p>创建命名元组子类的工厂函数</p></td>
</tr>
<tr class="row-even"><td><p><a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a></p></td>
<td><p>类似列表(list)的容器，实现了在两端快速添加(append)和弹出(pop)</p></td>
</tr>
<tr class="row-odd"><td><p><a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a></p></td>
<td><p>类似字典(dict)的容器类，将多个映射集合到一个视图里面</p></td>
</tr>
<tr class="row-even"><td><p><a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a></p></td>
<td><p>字典的子类，提供了可哈希对象的计数功能</p></td>
</tr>
<tr class="row-odd"><td><p><a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a></p></td>
<td><p>字典的子类，保存了他们被添加的顺序</p></td>
</tr>
<tr class="row-even"><td><p><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a></p></td>
<td><p>字典的子类，提供了一个工厂函数，为字典查询提供一个默认值</p></td>
</tr>
<tr class="row-odd"><td><p><a class="reference internal" href="#collections.UserDict" title="collections.UserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code></a></p></td>
<td><p>封装了字典对象，简化了字典子类化</p></td>
</tr>
<tr class="row-even"><td><p><a class="reference internal" href="#collections.UserList" title="collections.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a></p></td>
<td><p>封装了列表对象，简化了列表子类化</p></td>
</tr>
<tr class="row-odd"><td><p><a class="reference internal" href="#collections.UserString" title="collections.UserString"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code></a></p></td>
<td><p>封装了列表对象，简化了字符串子类化</p></td>
</tr>
</tbody>
</table>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 3.3, will be removed in version 3.9: </span>已将 <a class="reference internal" href="collections.abc.html#collections-abstract-base-classes"><span class="std std-ref">容器抽象基类</span></a> 移至 <a class="reference internal" href="collections.abc.html#module-collections.abc" title="collections.abc: Abstract base classes for containers"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections.abc</span></code></a> 模块。 为了保持向下兼容性，它们在 Python 3.8 版的这个模块中仍然存在.</p>
</div>
<div class="section" id="chainmap-objects">
<h2><a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a> 对象<a class="headerlink" href="#chainmap-objects" title="永久链接至标题">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能.</span></p>
</div>
<p>一个 <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a> 类是为了将多个映射快速的链接到一起，这样它们就可以作为一个单元处理。它通常比创建一个新字典和多次调用 <a class="reference internal" href="stdtypes.html#dict.update" title="dict.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code></a> 要快很多。</p>
<p>这个类可以用于模拟嵌套作用域，并且在模版化的时候比较有用。</p>
<dl class="class">
<dt id="collections.ChainMap">
<em class="property">class </em><code class="sig-prename descclassname">collections.</code><code class="sig-name descname">ChainMap</code><span class="sig-paren">(</span><em class="sig-param">*maps</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.ChainMap" title="永久链接至目标">¶</a></dt>
<dd><p>一个 <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a> 将多个字典或者其他映射组合在一起，创建一个单独的可更新的视图。  如果没有 <em>maps</em> 被指定，就提供一个默认的空字典，这样一个新链至少有一个映射。</p>
<p>底层映射被存储在一个列表中。这个列表是公开的，可以通过 <em>maps</em> 属性存取和更新。没有其他的状态。</p>
<p>搜索查询底层映射，直到一个键被找到。不同的是，写，更新和删除只操作第一个映射。</p>
<p>一个 <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a> 通过引用合并底层映射。 所以，如果一个底层映射更新了，这些更改会反映到 <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a> 。</p>
<p>支持所有常用字典方法。另外还有一个  <em>maps</em> 属性(attribute)，一个创建子上下文的方法(method)， 一个存取它们首个映射的属性(property):</p>
<dl class="attribute">
<dt id="collections.ChainMap.maps">
<code class="sig-name descname">maps</code><a class="headerlink" href="#collections.ChainMap.maps" title="永久链接至目标">¶</a></dt>
<dd><p>一个可以更新的映射列表。这个列表是按照第一次搜索到最后一次搜索的顺序组织的。它是仅有的存储状态，可以被修改。列表最少包含一个映射。</p>
</dd></dl>

<dl class="method">
<dt id="collections.ChainMap.new_child">
<code class="sig-name descname">new_child</code><span class="sig-paren">(</span><em class="sig-param">m=None</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.ChainMap.new_child" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个新的 <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a> 类，包含了一个新映射(map)，后面跟随当前实例的全部映射(map)。如果 <code class="docutils literal notranslate"><span class="pre">m</span></code> 被指定，它就成为不同新的实例，就是在所有映射前加上 m，如果没有指定，就加上一个空字典，这样的话一个 <code class="docutils literal notranslate"><span class="pre">d.new_child()</span></code> 调用等价于 <code class="docutils literal notranslate"><span class="pre">ChainMap({},</span> <span class="pre">*d.maps)</span></code> 。这个方法用于创建子上下文，不改变任何父映射的值。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.4 版更改: </span>添加了 <code class="docutils literal notranslate"><span class="pre">m</span></code>  可选参数。</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="collections.ChainMap.parents">
<code class="sig-name descname">parents</code><a class="headerlink" href="#collections.ChainMap.parents" title="永久链接至目标">¶</a></dt>
<dd><p>属性返回一个新的 <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a> 包含所有的当前实例的映射，除了第一个。这样可以在搜索的时候跳过第一个映射。 使用的场景类似在 <a class="reference internal" href="../glossary.html#term-nested-scope"><span class="xref std std-term">nested scopes</span></a> 嵌套作用域中使用 <a class="reference internal" href="../reference/simple_stmts.html#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a> 关键词。用例也可以类比内建函数  <a class="reference internal" href="functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a> 。一个 <code class="docutils literal notranslate"><span class="pre">d.parents</span></code> 的引用等价于 <code class="docutils literal notranslate"><span class="pre">ChainMap(*d.maps[1:])</span></code> 。</p>
</dd></dl>

<p>注意，一个 <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap()</span></code></a> 的迭代顺序是通过扫描最后的映射来确定的:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">baseline</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;music&#39;</span><span class="p">:</span> <span class="s1">&#39;bach&#39;</span><span class="p">,</span> <span class="s1">&#39;art&#39;</span><span class="p">:</span> <span class="s1">&#39;rembrandt&#39;</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">adjustments</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;art&#39;</span><span class="p">:</span> <span class="s1">&#39;van gogh&#39;</span><span class="p">,</span> <span class="s1">&#39;opera&#39;</span><span class="p">:</span> <span class="s1">&#39;carmen&#39;</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">ChainMap</span><span class="p">(</span><span class="n">adjustments</span><span class="p">,</span> <span class="n">baseline</span><span class="p">))</span>
<span class="go">[&#39;music&#39;, &#39;art&#39;, &#39;opera&#39;]</span>
</pre></div>
</div>
<p>这给出了与 <a class="reference internal" href="stdtypes.html#dict.update" title="dict.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.update()</span></code></a> 调用序列相同的顺序，从最后一个映射开始:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">combined</span> <span class="o">=</span> <span class="n">baseline</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">combined</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">adjustments</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">combined</span><span class="p">)</span>
<span class="go">[&#39;music&#39;, &#39;art&#39;, &#39;opera&#39;]</span>
</pre></div>
</div>
</dd></dl>

<div class="admonition seealso">
<p class="admonition-title">参见</p>
<ul class="simple">
<li><p><a class="reference external" href="https://github.com/enthought/codetools/blob/4.0.0/codetools/contexts/multi_context.py">MultiContext class</a> 在 Enthought <a class="reference external" href="https://github.com/enthought/codetools">CodeTools package</a> 有支持写映射的选项。</p></li>
<li><p>Django 的 <a class="reference external" href="https://github.com/django/django/blob/master/django/template/context.py">Context class</a> 模版是只读映射。它的上下文的push和pop特性也类似于 <a class="reference internal" href="#collections.ChainMap.new_child" title="collections.ChainMap.new_child"><code class="xref py py-meth docutils literal notranslate"><span class="pre">new_child()</span></code></a> 方法 <a class="reference internal" href="#collections.ChainMap.parents" title="collections.ChainMap.parents"><code class="xref py py-attr docutils literal notranslate"><span class="pre">parents</span></code></a> 属性。</p></li>
<li><p><a class="reference external" href="https://code.activestate.com/recipes/577434/">Nested Contexts recipe</a> 提供了是否对第一个映射或其他映射进行写和其他修改的选项。</p></li>
<li><p>一个 <a class="reference external" href="https://code.activestate.com/recipes/305268/">极简的只读版 Chainmap</a>.</p></li>
</ul>
</div>
<div class="section" id="chainmap-examples-and-recipes">
<h3><a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a> 例子和方法<a class="headerlink" href="#chainmap-examples-and-recipes" title="永久链接至标题">¶</a></h3>
<p>这一节提供了多个使用链映射的案例。</p>
<p>模拟Python内部lookup链的例子</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">builtins</span>
<span class="n">pylookup</span> <span class="o">=</span> <span class="n">ChainMap</span><span class="p">(</span><span class="nb">locals</span><span class="p">(),</span> <span class="nb">globals</span><span class="p">(),</span> <span class="nb">vars</span><span class="p">(</span><span class="n">builtins</span><span class="p">))</span>
</pre></div>
</div>
<p>让用户指定的命令行参数优先于环境变量，优先于默认值的例子</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span><span class="o">,</span> <span class="nn">argparse</span>

<span class="n">defaults</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;color&#39;</span><span class="p">:</span> <span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="s1">&#39;user&#39;</span><span class="p">:</span> <span class="s1">&#39;guest&#39;</span><span class="p">}</span>

<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-u&#39;</span><span class="p">,</span> <span class="s1">&#39;--user&#39;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-c&#39;</span><span class="p">,</span> <span class="s1">&#39;--color&#39;</span><span class="p">)</span>
<span class="n">namespace</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="n">command_line_args</span> <span class="o">=</span> <span class="p">{</span><span class="n">k</span><span class="p">:</span> <span class="n">v</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="nb">vars</span><span class="p">(</span><span class="n">namespace</span><span class="p">)</span><span class="o">.</span><span class="n">items</span><span class="p">()</span> <span class="k">if</span> <span class="n">v</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">}</span>

<span class="n">combined</span> <span class="o">=</span> <span class="n">ChainMap</span><span class="p">(</span><span class="n">command_line_args</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">,</span> <span class="n">defaults</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">combined</span><span class="p">[</span><span class="s1">&#39;color&#39;</span><span class="p">])</span>
<span class="nb">print</span><span class="p">(</span><span class="n">combined</span><span class="p">[</span><span class="s1">&#39;user&#39;</span><span class="p">])</span>
</pre></div>
</div>
<p>用 <a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a> 类模拟嵌套上下文的例子</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">c</span> <span class="o">=</span> <span class="n">ChainMap</span><span class="p">()</span>        <span class="c1"># Create root context</span>
<span class="n">d</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="n">new_child</span><span class="p">()</span>     <span class="c1"># Create nested child context</span>
<span class="n">e</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="n">new_child</span><span class="p">()</span>     <span class="c1"># Child of c, independent from d</span>
<span class="n">e</span><span class="o">.</span><span class="n">maps</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>             <span class="c1"># Current context dictionary -- like Python&#39;s locals()</span>
<span class="n">e</span><span class="o">.</span><span class="n">maps</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>            <span class="c1"># Root context -- like Python&#39;s globals()</span>
<span class="n">e</span><span class="o">.</span><span class="n">parents</span>             <span class="c1"># Enclosing context chain -- like Python&#39;s nonlocals</span>

<span class="n">d</span><span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span>            <span class="c1"># Set value in current context</span>
<span class="n">d</span><span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">]</span>                <span class="c1"># Get first key in the chain of contexts</span>
<span class="k">del</span> <span class="n">d</span><span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">]</span>            <span class="c1"># Delete from current context</span>
<span class="nb">list</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>               <span class="c1"># All nested values</span>
<span class="n">k</span> <span class="ow">in</span> <span class="n">d</span>                <span class="c1"># Check all nested values</span>
<span class="nb">len</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>                <span class="c1"># Number of nested values</span>
<span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>             <span class="c1"># All nested items</span>
<span class="nb">dict</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>               <span class="c1"># Flatten into a regular dictionary</span>
</pre></div>
</div>
<p><a class="reference internal" href="#collections.ChainMap" title="collections.ChainMap"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code></a> 类只更新链中的第一个映射，但lookup会搜索整个链。 然而，如果需要深度写和删除，也可以很容易的通过定义一个子类来实现它</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DeepChainMap</span><span class="p">(</span><span class="n">ChainMap</span><span class="p">):</span>
    <span class="s1">&#39;Variant of ChainMap that allows direct updates to inner scopes&#39;</span>

    <span class="k">def</span> <span class="fm">__setitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="k">for</span> <span class="n">mapping</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">maps</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">mapping</span><span class="p">:</span>
                <span class="n">mapping</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">value</span>
                <span class="k">return</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">maps</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">value</span>

    <span class="k">def</span> <span class="fm">__delitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
        <span class="k">for</span> <span class="n">mapping</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">maps</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">mapping</span><span class="p">:</span>
                <span class="k">del</span> <span class="n">mapping</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
                <span class="k">return</span>
        <span class="k">raise</span> <span class="ne">KeyError</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>

<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span> <span class="o">=</span> <span class="n">DeepChainMap</span><span class="p">({</span><span class="s1">&#39;zebra&#39;</span><span class="p">:</span> <span class="s1">&#39;black&#39;</span><span class="p">},</span> <span class="p">{</span><span class="s1">&#39;elephant&#39;</span><span class="p">:</span> <span class="s1">&#39;blue&#39;</span><span class="p">},</span> <span class="p">{</span><span class="s1">&#39;lion&#39;</span><span class="p">:</span> <span class="s1">&#39;yellow&#39;</span><span class="p">})</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span><span class="p">[</span><span class="s1">&#39;lion&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;orange&#39;</span>         <span class="c1"># update an existing key two levels down</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span><span class="p">[</span><span class="s1">&#39;snake&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;red&#39;</span>           <span class="c1"># new keys get added to the topmost dict</span>
<span class="o">&gt;&gt;&gt;</span> <span class="k">del</span> <span class="n">d</span><span class="p">[</span><span class="s1">&#39;elephant&#39;</span><span class="p">]</span>            <span class="c1"># remove an existing key one level down</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span>                            <span class="c1"># display result</span>
<span class="n">DeepChainMap</span><span class="p">({</span><span class="s1">&#39;zebra&#39;</span><span class="p">:</span> <span class="s1">&#39;black&#39;</span><span class="p">,</span> <span class="s1">&#39;snake&#39;</span><span class="p">:</span> <span class="s1">&#39;red&#39;</span><span class="p">},</span> <span class="p">{},</span> <span class="p">{</span><span class="s1">&#39;lion&#39;</span><span class="p">:</span> <span class="s1">&#39;orange&#39;</span><span class="p">})</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="counter-objects">
<h2><a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> 对象<a class="headerlink" href="#counter-objects" title="永久链接至标题">¶</a></h2>
<p>一个计数器工具提供快速和方便的计数。比如</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Tally occurrences of words in a list</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cnt</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="s1">&#39;green&#39;</span><span class="p">,</span> <span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="s1">&#39;blue&#39;</span><span class="p">]:</span>
<span class="gp">... </span>    <span class="n">cnt</span><span class="p">[</span><span class="n">word</span><span class="p">]</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cnt</span>
<span class="go">Counter({&#39;blue&#39;: 3, &#39;red&#39;: 2, &#39;green&#39;: 1})</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Find the ten most common words in Hamlet</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">re</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">words</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\w+&#39;</span><span class="p">,</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;hamlet.txt&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">()</span><span class="o">.</span><span class="n">lower</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Counter</span><span class="p">(</span><span class="n">words</span><span class="p">)</span><span class="o">.</span><span class="n">most_common</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="go">[(&#39;the&#39;, 1143), (&#39;and&#39;, 966), (&#39;to&#39;, 762), (&#39;of&#39;, 669), (&#39;i&#39;, 631),</span>
<span class="go"> (&#39;you&#39;, 554),  (&#39;a&#39;, 546), (&#39;my&#39;, 514), (&#39;hamlet&#39;, 471), (&#39;in&#39;, 451)]</span>
</pre></div>
</div>
<dl class="class">
<dt id="collections.Counter">
<em class="property">class </em><code class="sig-prename descclassname">collections.</code><code class="sig-name descname">Counter</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">iterable-or-mapping</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter" title="永久链接至目标">¶</a></dt>
<dd><p>一个 <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> 是一个 <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 的子类，用于计数可哈希对象。它是一个集合，元素像字典键(key)一样存储，它们的计数存储为值。计数可以是任何整数值，包括0和负数。 <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> 类有点像其他语言中的 bags或multisets。</p>
<p>元素从一个 <em>iterable</em> 被计数或从其他的 <em>mapping</em> (or counter)初始化：</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">()</span>                           <span class="c1"># a new, empty counter</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="s1">&#39;gallahad&#39;</span><span class="p">)</span>                 <span class="c1"># a new counter from an iterable</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">({</span><span class="s1">&#39;red&#39;</span><span class="p">:</span> <span class="mi">4</span><span class="p">,</span> <span class="s1">&#39;blue&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">})</span>      <span class="c1"># a new counter from a mapping</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">cats</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">dogs</span><span class="o">=</span><span class="mi">8</span><span class="p">)</span>             <span class="c1"># a new counter from keyword args</span>
</pre></div>
</div>
<p>Counter对象有一个字典接口，如果引用的键没有任何记录，就返回一个0，而不是弹出一个 <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> :</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">([</span><span class="s1">&#39;eggs&#39;</span><span class="p">,</span> <span class="s1">&#39;ham&#39;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s1">&#39;bacon&#39;</span><span class="p">]</span>                              <span class="c1"># count of a missing element is zero</span>
<span class="go">0</span>
</pre></div>
</div>
<p>设置一个计数为0不会从计数器中移去一个元素。使用 <code class="docutils literal notranslate"><span class="pre">del</span></code> 来删除它:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s1">&#39;sausage&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">0</span>                        <span class="c1"># counter entry with a zero count</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">c</span><span class="p">[</span><span class="s1">&#39;sausage&#39;</span><span class="p">]</span>                        <span class="c1"># del actually removes the entry</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.1 新版功能.</span></p>
</div>
<p>计数器对象除了字典方法以外，还提供了三个其他的方法：</p>
<dl class="method">
<dt id="collections.Counter.elements">
<code class="sig-name descname">elements</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter.elements" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个迭代器，每个元素重复计数的个数。元素顺序是任意的。如果一个元素的计数小于1， <a class="reference internal" href="#collections.Counter.elements" title="collections.Counter.elements"><code class="xref py py-meth docutils literal notranslate"><span class="pre">elements()</span></code></a> 就会忽略它。</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">c</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">d</span><span class="o">=-</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">elements</span><span class="p">())</span>
<span class="go">[&#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;b&#39;, &#39;b&#39;]</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.Counter.most_common">
<code class="sig-name descname">most_common</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">n</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter.most_common" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个列表，提供  <em>n</em> 个频率最高的元素和计数。 如果没提供 <em>n</em> ，或者是 <code class="docutils literal notranslate"><span class="pre">None</span></code> ， <a class="reference internal" href="#collections.Counter.most_common" title="collections.Counter.most_common"><code class="xref py py-meth docutils literal notranslate"><span class="pre">most_common()</span></code></a> 返回计数器中的 <em>所有</em> 元素。相等个数的元素顺序随机：</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Counter</span><span class="p">(</span><span class="s1">&#39;abracadabra&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">most_common</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>  
<span class="go">[(&#39;a&#39;, 5), (&#39;r&#39;, 2), (&#39;b&#39;, 2)]</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.Counter.subtract">
<code class="sig-name descname">subtract</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">iterable-or-mapping</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter.subtract" title="永久链接至目标">¶</a></dt>
<dd><p>从 <em>迭代对象</em> 或 <em>映射对象</em> 减去元素。像 <a class="reference internal" href="stdtypes.html#dict.update" title="dict.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.update()</span></code></a> 但是是减去，而不是替换。输入和输出都可以是0或者负数。</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">c</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">d</span><span class="o">=-</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">c</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">d</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">subtract</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span>
<span class="go">Counter({&#39;a&#39;: 3, &#39;b&#39;: 0, &#39;c&#39;: -3, &#39;d&#39;: -6})</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
</dd></dl>

<p>通常字典方法都可用于 <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> 对象，除了有两个方法工作方式与字典并不相同。</p>
<dl class="method">
<dt id="collections.Counter.fromkeys">
<code class="sig-name descname">fromkeys</code><span class="sig-paren">(</span><em class="sig-param">iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter.fromkeys" title="永久链接至目标">¶</a></dt>
<dd><p>这个类方法没有在 <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> 中实现。</p>
</dd></dl>

<dl class="method">
<dt id="collections.Counter.update">
<code class="sig-name descname">update</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">iterable-or-mapping</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter.update" title="永久链接至目标">¶</a></dt>
<dd><p>从 <em>迭代对象</em> 计数元素或者 从另一个 <em>映射对象</em> (或计数器) 添加。 像 <a class="reference internal" href="stdtypes.html#dict.update" title="dict.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.update()</span></code></a> 但是是加上，而不是替换。另外，<em>迭代对象</em> 应该是序列元素，而不是一个 <code class="docutils literal notranslate"><span class="pre">(key,</span> <span class="pre">value)</span></code> 对。</p>
</dd></dl>

</dd></dl>

<p><a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> 对象的常用案例</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nb">sum</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">values</span><span class="p">())</span>                 <span class="c1"># total of all counts</span>
<span class="n">c</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>                       <span class="c1"># reset all counts</span>
<span class="nb">list</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>                         <span class="c1"># list unique elements</span>
<span class="nb">set</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>                          <span class="c1"># convert to a set</span>
<span class="nb">dict</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>                         <span class="c1"># convert to a regular dictionary</span>
<span class="n">c</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>                       <span class="c1"># convert to a list of (elem, cnt) pairs</span>
<span class="n">Counter</span><span class="p">(</span><span class="nb">dict</span><span class="p">(</span><span class="n">list_of_pairs</span><span class="p">))</span>    <span class="c1"># convert from a list of (elem, cnt) pairs</span>
<span class="n">c</span><span class="o">.</span><span class="n">most_common</span><span class="p">()[:</span><span class="o">-</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">:</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>       <span class="c1"># n least common elements</span>
<span class="o">+</span><span class="n">c</span>                              <span class="c1"># remove zero and negative counts</span>
</pre></div>
</div>
<p>提供了几个数学操作，可以结合  <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> 对象，以生产 multisets (计数器中大于0的元素）。 加和减，结合计数器，通过加上或者减去元素的相应计数。交集和并集返回相应计数的最小或最大值。每种操作都可以接受带符号的计数，但是输出会忽略掉结果为零或者小于零的计数。</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">+</span> <span class="n">d</span>                       <span class="c1"># add two counters together:  c[x] + d[x]</span>
<span class="go">Counter({&#39;a&#39;: 4, &#39;b&#39;: 3})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">-</span> <span class="n">d</span>                       <span class="c1"># subtract (keeping only positive counts)</span>
<span class="go">Counter({&#39;a&#39;: 2})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">&amp;</span> <span class="n">d</span>                       <span class="c1"># intersection:  min(c[x], d[x]) </span>
<span class="go">Counter({&#39;a&#39;: 1, &#39;b&#39;: 1})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">|</span> <span class="n">d</span>                       <span class="c1"># union:  max(c[x], d[x])</span>
<span class="go">Counter({&#39;a&#39;: 3, &#39;b&#39;: 2})</span>
</pre></div>
</div>
<p>单目加和减（一元操作符）意思是从空计数器加或者减去。</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">b</span><span class="o">=-</span><span class="mi">4</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="o">+</span><span class="n">c</span>
<span class="go">Counter({&#39;a&#39;: 2})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="o">-</span><span class="n">c</span>
<span class="go">Counter({&#39;b&#39;: 4})</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.3 新版功能: </span>添加了对一元加，一元减和位置集合操作的支持。</p>
</div>
<div class="admonition note">
<p class="admonition-title">注解</p>
<p>计数器主要是为了表达运行的正的计数而设计；但是，小心不要预先排除负数或者其他类型。为了帮助这些用例，这一节记录了最小范围和类型限制。</p>
<ul class="simple">
<li><p><a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> 类是一个字典的子类，不限制键和值。值用于表示计数，但你实际上 <em>可以</em> 存储任何其他值。</p></li>
<li><p><a class="reference internal" href="#collections.Counter.most_common" title="collections.Counter.most_common"><code class="xref py py-meth docutils literal notranslate"><span class="pre">most_common()</span></code></a> 方法在值需要排序的时候用。</p></li>
<li><p>原地操作比如 <code class="docutils literal notranslate"><span class="pre">c[key]</span> <span class="pre">+=</span> <span class="pre">1</span></code> ， 值类型只需要支持加和减。 所以分数，小数，和十进制都可以用，负值也可以支持。这两个方法 <a class="reference internal" href="#collections.Counter.update" title="collections.Counter.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code></a> 和 <a class="reference internal" href="#collections.Counter.subtract" title="collections.Counter.subtract"><code class="xref py py-meth docutils literal notranslate"><span class="pre">subtract()</span></code></a> 的输入和输出也一样支持负数和0。</p></li>
<li><p>Multiset多集合方法只为正值的使用情况设计。输入可以是负数或者0，但只输出计数为正的值。没有类型限制，但值类型需要支持加，减和比较操作。</p></li>
<li><p><a class="reference internal" href="#collections.Counter.elements" title="collections.Counter.elements"><code class="xref py py-meth docutils literal notranslate"><span class="pre">elements()</span></code></a> 方法要求正整数计数。忽略0和负数计数。</p></li>
</ul>
</div>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<ul>
<li><p><a class="reference external" href="https://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html">Bag class</a> 在 Smalltalk。</p></li>
<li><p>Wikipedia 链接 <a class="reference external" href="https://en.wikipedia.org/wiki/Multiset">Multisets</a>.</p></li>
<li><p><a class="reference external" href="http://www.java2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm">C++ multisets</a> 教程和例子。</p></li>
<li><p>数学操作和多集合用例，参考 <em>Knuth, Donald. The Art of Computer Programming Volume II, Section 4.6.3, Exercise 19</em> 。</p></li>
<li><p>在给定数量和集合元素枚举所有不同的多集合，参考 <a class="reference internal" href="itertools.html#itertools.combinations_with_replacement" title="itertools.combinations_with_replacement"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.combinations_with_replacement()</span></code></a></p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="nb">map</span><span class="p">(</span><span class="n">Counter</span><span class="p">,</span> <span class="n">combinations_with_replacement</span><span class="p">(</span><span class="s1">&#39;ABC&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span> <span class="c1"># --&gt; AA AB AC BB BC CC</span>
</pre></div>
</div>
</li>
</ul>
</div>
</div>
<div class="section" id="deque-objects">
<h2><a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> 对象<a class="headerlink" href="#deque-objects" title="永久链接至标题">¶</a></h2>
<dl class="class">
<dt id="collections.deque">
<em class="property">class </em><code class="sig-prename descclassname">collections.</code><code class="sig-name descname">deque</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">iterable</em><span class="optional">[</span>, <em class="sig-param">maxlen</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个新的双向队列对象，从左到右初始化(用方法 <a class="reference internal" href="#collections.deque.append" title="collections.deque.append"><code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code></a>) ，从 <em>iterable</em> （迭代对象) 数据创建。如果 <em>iterable</em> 没有指定，新队列为空。</p>
<p>Deque队列是由栈或者queue队列生成的（发音是 “deck”，”double-ended queue”的简称）。Deque 支持线程安全，内存高效添加(append)和弹出(pop)，从两端都可以，两个方向的大概开销都是 O(1) 复杂度。</p>
<p>虽然 <a class="reference internal" href="stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a> 对象也支持类似操作，不过这里优化了定长操作和 <code class="docutils literal notranslate"><span class="pre">pop(0)</span></code> 和 <code class="docutils literal notranslate"><span class="pre">insert(0,</span> <span class="pre">v)</span></code> 的开销。它们引起 O(n) 内存移动的操作，改变底层数据表达的大小和位置。</p>
<p>如果 <em>maxlen</em> 没有指定或者是 <code class="docutils literal notranslate"><span class="pre">None</span></code> ，deques 可以增长到任意长度。否则，deque就限定到指定最大长度。一旦限定长度的deque满了，当新项加入时，同样数量的项就从另一端弹出。限定长度deque提供类似Unix filter <code class="docutils literal notranslate"><span class="pre">tail</span></code> 的功能。它们同样可以用与追踪最近的交换和其他数据池活动。</p>
<p>双向队列(deque)对象支持以下方法：</p>
<dl class="method">
<dt id="collections.deque.append">
<code class="sig-name descname">append</code><span class="sig-paren">(</span><em class="sig-param">x</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.append" title="永久链接至目标">¶</a></dt>
<dd><p>添加 <em>x</em> 到右端。</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.appendleft">
<code class="sig-name descname">appendleft</code><span class="sig-paren">(</span><em class="sig-param">x</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.appendleft" title="永久链接至目标">¶</a></dt>
<dd><p>添加 <em>x</em> 到左端。</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.clear">
<code class="sig-name descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.clear" title="永久链接至目标">¶</a></dt>
<dd><p>移除所有元素，使其长度为0.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.copy">
<code class="sig-name descname">copy</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.copy" title="永久链接至目标">¶</a></dt>
<dd><p>创建一份浅拷贝。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.5 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.deque.count">
<code class="sig-name descname">count</code><span class="sig-paren">(</span><em class="sig-param">x</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.count" title="永久链接至目标">¶</a></dt>
<dd><p>计算 deque 中元素等于 <em>x</em> 的个数。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.deque.extend">
<code class="sig-name descname">extend</code><span class="sig-paren">(</span><em class="sig-param">iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.extend" title="永久链接至目标">¶</a></dt>
<dd><p>扩展deque的右侧，通过添加iterable参数中的元素。</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.extendleft">
<code class="sig-name descname">extendleft</code><span class="sig-paren">(</span><em class="sig-param">iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.extendleft" title="永久链接至目标">¶</a></dt>
<dd><p>扩展deque的左侧，通过添加iterable参数中的元素。注意，左添加时，在结果中iterable参数中的顺序将被反过来添加。</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.index">
<code class="sig-name descname">index</code><span class="sig-paren">(</span><em class="sig-param">x</em><span class="optional">[</span>, <em class="sig-param">start</em><span class="optional">[</span>, <em class="sig-param">stop</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.index" title="永久链接至目标">¶</a></dt>
<dd><p>返回 <em>x</em> 在 deque 中的位置（在索引 <em>start</em> 之后，索引 <em>stop</em> 之前）。 返回第一个匹配项，如果未找到则引发 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.5 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.deque.insert">
<code class="sig-name descname">insert</code><span class="sig-paren">(</span><em class="sig-param">i</em>, <em class="sig-param">x</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.insert" title="永久链接至目标">¶</a></dt>
<dd><p>在位置 <em>i</em> 插入 <em>x</em> 。</p>
<p>如果插入会导致一个限长 deque 超出长度 <em>maxlen</em> 的话，就引发一个 <a class="reference internal" href="exceptions.html#IndexError" title="IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a>。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.5 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.deque.pop">
<code class="sig-name descname">pop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.pop" title="永久链接至目标">¶</a></dt>
<dd><p>移去并且返回一个元素，deque 最右侧的那一个。 如果没有元素的话，就引发一个 <a class="reference internal" href="exceptions.html#IndexError" title="IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.popleft">
<code class="sig-name descname">popleft</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.popleft" title="永久链接至目标">¶</a></dt>
<dd><p>移去并且返回一个元素，deque 最左侧的那一个。 如果没有元素的话，就引发 <a class="reference internal" href="exceptions.html#IndexError" title="IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.remove">
<code class="sig-name descname">remove</code><span class="sig-paren">(</span><em class="sig-param">value</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.remove" title="永久链接至目标">¶</a></dt>
<dd><p>移除找到的第一个 <em>value</em>。 如果没有的话就引发 <a class="reference internal" href="exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.reverse">
<code class="sig-name descname">reverse</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.reverse" title="永久链接至目标">¶</a></dt>
<dd><p>将deque逆序排列。返回 <code class="docutils literal notranslate"><span class="pre">None</span></code> 。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.deque.rotate">
<code class="sig-name descname">rotate</code><span class="sig-paren">(</span><em class="sig-param">n=1</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.rotate" title="永久链接至目标">¶</a></dt>
<dd><p>向右循环移动 <em>n</em> 步。 如果 <em>n</em> 是负数，就向左循环。</p>
<p>如果deque不是空的，向右循环移动一步就等价于 <code class="docutils literal notranslate"><span class="pre">d.appendleft(d.pop())</span></code> ， 向左循环一步就等价于 <code class="docutils literal notranslate"><span class="pre">d.append(d.popleft())</span></code> 。</p>
</dd></dl>

<p>Deque对象同样提供了一个只读属性:</p>
<dl class="attribute">
<dt id="collections.deque.maxlen">
<code class="sig-name descname">maxlen</code><a class="headerlink" href="#collections.deque.maxlen" title="永久链接至目标">¶</a></dt>
<dd><p>Deque的最大尺寸，如果没有限定的话就是 <code class="docutils literal notranslate"><span class="pre">None</span></code> 。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.1 新版功能.</span></p>
</div>
</dd></dl>

</dd></dl>

<p>除了以上，deque还支持迭代，清洗，<code class="docutils literal notranslate"><span class="pre">len(d)</span></code>, <code class="docutils literal notranslate"><span class="pre">reversed(d)</span></code>, <code class="docutils literal notranslate"><span class="pre">copy.copy(d)</span></code>, <code class="docutils literal notranslate"><span class="pre">copy.deepcopy(d)</span></code>, 成员测试 <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> 操作符，和下标引用 <code class="docutils literal notranslate"><span class="pre">d[-1]</span></code> 。索引存取在两端的复杂度是 O(1)， 在中间的复杂度比 O(n) 略低。要快速存取，使用list来替代。</p>
<p>Deque从版本3.5开始支持 <code class="docutils literal notranslate"><span class="pre">__add__()</span></code>, <code class="docutils literal notranslate"><span class="pre">__mul__()</span></code>, 和 <code class="docutils literal notranslate"><span class="pre">__imul__()</span></code> 。</p>
<p>示例:</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">deque</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">deque</span><span class="p">(</span><span class="s1">&#39;ghi&#39;</span><span class="p">)</span>                 <span class="c1"># make a new deque with three items</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">d</span><span class="p">:</span>                   <span class="c1"># iterate over the deque&#39;s elements</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">elem</span><span class="o">.</span><span class="n">upper</span><span class="p">())</span>
<span class="go">G</span>
<span class="go">H</span>
<span class="go">I</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">&#39;j&#39;</span><span class="p">)</span>                    <span class="c1"># add a new entry to the right side</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">appendleft</span><span class="p">(</span><span class="s1">&#39;f&#39;</span><span class="p">)</span>                <span class="c1"># add a new entry to the left side</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>                                <span class="c1"># show the representation of the deque</span>
<span class="go">deque([&#39;f&#39;, &#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>                          <span class="c1"># return and remove the rightmost item</span>
<span class="go">&#39;j&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>                      <span class="c1"># return and remove the leftmost item</span>
<span class="go">&#39;f&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>                          <span class="c1"># list the contents of the deque</span>
<span class="go">[&#39;g&#39;, &#39;h&#39;, &#39;i&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>                             <span class="c1"># peek at leftmost item</span>
<span class="go">&#39;g&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>                            <span class="c1"># peek at rightmost item</span>
<span class="go">&#39;i&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">reversed</span><span class="p">(</span><span class="n">d</span><span class="p">))</span>                <span class="c1"># list the contents of a deque in reverse</span>
<span class="go">[&#39;i&#39;, &#39;h&#39;, &#39;g&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;h&#39;</span> <span class="ow">in</span> <span class="n">d</span>                         <span class="c1"># search the deque</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="s1">&#39;jkl&#39;</span><span class="p">)</span>                  <span class="c1"># add multiple elements at once</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">deque([&#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;, &#39;k&#39;, &#39;l&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>                      <span class="c1"># right rotation</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">deque([&#39;l&#39;, &#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;, &#39;k&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>                     <span class="c1"># left rotation</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">deque([&#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;, &#39;k&#39;, &#39;l&#39;])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">deque</span><span class="p">(</span><span class="nb">reversed</span><span class="p">(</span><span class="n">d</span><span class="p">))</span>               <span class="c1"># make a new deque in reverse order</span>
<span class="go">deque([&#39;l&#39;, &#39;k&#39;, &#39;j&#39;, &#39;i&#39;, &#39;h&#39;, &#39;g&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>                        <span class="c1"># empty the deque</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>                          <span class="c1"># cannot pop from an empty deque</span>
<span class="gt">Traceback (most recent call last):</span>
    <span class="n">File</span> <span class="s2">&quot;&lt;pyshell#6&gt;&quot;</span><span class="p">,</span> <span class="n">line</span> <span class="mi">1</span><span class="p">,</span> <span class="ow">in</span> <span class="o">-</span><span class="n">toplevel</span><span class="o">-</span>
        <span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="gr">IndexError</span>: <span class="n">pop from an empty deque</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">extendleft</span><span class="p">(</span><span class="s1">&#39;abc&#39;</span><span class="p">)</span>              <span class="c1"># extendleft() reverses the input order</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">deque([&#39;c&#39;, &#39;b&#39;, &#39;a&#39;])</span>
</pre></div>
</div>
<div class="section" id="deque-recipes">
<h3><a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> 用法<a class="headerlink" href="#deque-recipes" title="永久链接至标题">¶</a></h3>
<p>这一节展示了deque的多种用法。</p>
<p>限长deque提供了类似Unix <code class="docutils literal notranslate"><span class="pre">tail</span></code> 过滤功能</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">tail</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">n</span><span class="o">=</span><span class="mi">10</span><span class="p">):</span>
    <span class="s1">&#39;Return the last n lines of a file&#39;</span>
    <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">deque</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">n</span><span class="p">)</span>
</pre></div>
</div>
<p>另一个用法是维护一个近期添加元素的序列，通过从右边添加和从左边弹出</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">moving_average</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">n</span><span class="o">=</span><span class="mi">3</span><span class="p">):</span>
    <span class="c1"># moving_average([40, 30, 50, 46, 39, 44]) --&gt; 40.0 42.0 45.0 43.0</span>
    <span class="c1"># http://en.wikipedia.org/wiki/Moving_average</span>
    <span class="n">it</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
    <span class="n">d</span> <span class="o">=</span> <span class="n">deque</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">islice</span><span class="p">(</span><span class="n">it</span><span class="p">,</span> <span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">))</span>
    <span class="n">d</span><span class="o">.</span><span class="n">appendleft</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
    <span class="n">s</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">it</span><span class="p">:</span>
        <span class="n">s</span> <span class="o">+=</span> <span class="n">elem</span> <span class="o">-</span> <span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>
        <span class="n">d</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">elem</span><span class="p">)</span>
        <span class="k">yield</span> <span class="n">s</span> <span class="o">/</span> <span class="n">n</span>
</pre></div>
</div>
<p>一个 <a class="reference external" href="https://en.wikipedia.org/wiki/Round-robin_scheduling">轮询调度器</a> 可以通过在 <a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> 中放入迭代器来实现。值从当前迭代器的位置0被取出并暂存(yield)。 如果这个迭代器消耗完毕，就用 <a class="reference internal" href="#collections.deque.popleft" title="collections.deque.popleft"><code class="xref py py-meth docutils literal notranslate"><span class="pre">popleft()</span></code></a> 将其从对列中移去；否则，就通过  <a class="reference internal" href="#collections.deque.rotate" title="collections.deque.rotate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">rotate()</span></code></a> 将它移到队列的末尾</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">roundrobin</span><span class="p">(</span><span class="o">*</span><span class="n">iterables</span><span class="p">):</span>
    <span class="s2">&quot;roundrobin(&#39;ABC&#39;, &#39;D&#39;, &#39;EF&#39;) --&gt; A D E B F C&quot;</span>
    <span class="n">iterators</span> <span class="o">=</span> <span class="n">deque</span><span class="p">(</span><span class="nb">map</span><span class="p">(</span><span class="nb">iter</span><span class="p">,</span> <span class="n">iterables</span><span class="p">))</span>
    <span class="k">while</span> <span class="n">iterators</span><span class="p">:</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
                <span class="k">yield</span> <span class="nb">next</span><span class="p">(</span><span class="n">iterators</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
                <span class="n">iterators</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>
        <span class="k">except</span> <span class="ne">StopIteration</span><span class="p">:</span>
            <span class="c1"># Remove an exhausted iterator.</span>
            <span class="n">iterators</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>
</pre></div>
</div>
<p><a class="reference internal" href="#collections.deque.rotate" title="collections.deque.rotate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">rotate()</span></code></a> 方法提供了一种方式来实现 <a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> 切片和删除。 例如， 一个纯的Python <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">d[n]</span></code> 实现依赖于 <code class="docutils literal notranslate"><span class="pre">rotate()</span></code> 来定位要弹出的元素</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">delete_nth</span><span class="p">(</span><span class="n">d</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
    <span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="o">-</span><span class="n">n</span><span class="p">)</span>
    <span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>
    <span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
</pre></div>
</div>
<p>要实现 <a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> 切片， 使用一个类似的方法，应用 <a class="reference internal" href="#collections.deque.rotate" title="collections.deque.rotate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">rotate()</span></code></a> 将目标元素放到左边。通过 <a class="reference internal" href="#collections.deque.popleft" title="collections.deque.popleft"><code class="xref py py-meth docutils literal notranslate"><span class="pre">popleft()</span></code></a> 移去老的条目（entries），通过 <a class="reference internal" href="#collections.deque.extend" title="collections.deque.extend"><code class="xref py py-meth docutils literal notranslate"><span class="pre">extend()</span></code></a> 添加新的条目， 然后反向 rotate。这个方法可以最小代价实现命令式的栈操作，诸如 <code class="docutils literal notranslate"><span class="pre">dup</span></code>, <code class="docutils literal notranslate"><span class="pre">drop</span></code>, <code class="docutils literal notranslate"><span class="pre">swap</span></code>, <code class="docutils literal notranslate"><span class="pre">over</span></code>, <code class="docutils literal notranslate"><span class="pre">pick</span></code>, <code class="docutils literal notranslate"><span class="pre">rot</span></code>, 和 <code class="docutils literal notranslate"><span class="pre">roll</span></code> 。</p>
</div>
</div>
<div class="section" id="defaultdict-objects">
<h2><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> 对象<a class="headerlink" href="#defaultdict-objects" title="永久链接至标题">¶</a></h2>
<dl class="class">
<dt id="collections.defaultdict">
<em class="property">class </em><code class="sig-prename descclassname">collections.</code><code class="sig-name descname">defaultdict</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">default_factory</em><span class="optional">[</span>, <em class="sig-param">...</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.defaultdict" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个新的类似字典的对象。 <a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> 是内置 <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 类的子类。它重载了一个方法并添加了一个可写的实例变量。其余的功能与 <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 类相同，此处不再重复说明。</p>
<p>第一个参数 <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> 提供了一个初始值。它默认为 <code class="docutils literal notranslate"><span class="pre">None</span></code> 。所有的其他参数都等同与 <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 构建器中的参数对待，包括关键词参数。</p>
<p><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> 对象除了支持 <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 的操作，还支持下面的方法作为扩展:</p>
<dl class="method">
<dt id="collections.defaultdict.__missing__">
<code class="sig-name descname">__missing__</code><span class="sig-paren">(</span><em class="sig-param">key</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.defaultdict.__missing__" title="永久链接至目标">¶</a></dt>
<dd><p>如果 <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> 属性为 <code class="docutils literal notranslate"><span class="pre">None</span></code>，则调用本方法会抛出 <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> 异常，附带参数 <em>key</em>。</p>
<p>如果 <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> 不为 <code class="docutils literal notranslate"><span class="pre">None</span></code> ， 它就会会被调用，不带参数，为 <em>key</em> 提供一个默认值， 这个值和 <em>key</em> 作为一个对被插入到字典中，并返回。</p>
<p>如果调用 <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> 时抛出了异常，这个异常会原封不动地向外层传递。</p>
<p>在无法找到所需键值时，本方法会被 <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 中的 <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> 方法调用。无论本方法返回了值还是抛出了异常，都会被 <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> 传递。</p>
<p>注意 <a class="reference internal" href="#collections.defaultdict.__missing__" title="collections.defaultdict.__missing__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__missing__()</span></code></a> <em>不会</em> 被 <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> 以外的其他方法调用。意思就是 <code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code> 会向正常的dict那样返回 <code class="docutils literal notranslate"><span class="pre">None</span></code> ，而不是使用 <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> 。</p>
</dd></dl>

<p><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> 支持以下实例变量:</p>
<dl class="attribute">
<dt id="collections.defaultdict.default_factory">
<code class="sig-name descname">default_factory</code><a class="headerlink" href="#collections.defaultdict.default_factory" title="永久链接至目标">¶</a></dt>
<dd><p>这个属性被 <a class="reference internal" href="#collections.defaultdict.__missing__" title="collections.defaultdict.__missing__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__missing__()</span></code></a> 方法使用；它从构建器的第一个参数初始化，如果提供了的话，否则就是 <code class="docutils literal notranslate"><span class="pre">None</span></code> 。</p>
</dd></dl>

</dd></dl>

<div class="section" id="defaultdict-examples">
<h3><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> 例子<a class="headerlink" href="#defaultdict-examples" title="永久链接至标题">¶</a></h3>
<p>使用 <a class="reference internal" href="stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a> 作为 <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> ，很容易将序列作为键值对加入字典:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;yellow&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;yellow&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="nb">list</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">d</span><span class="p">[</span><span class="n">k</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">())</span>
<span class="go">[(&#39;blue&#39;, [2, 4]), (&#39;red&#39;, [1]), (&#39;yellow&#39;, [1, 3])]</span>
</pre></div>
</div>
<p>当每个键第一次遇见时，它还没有在字典里面；所以条目自动创建，通过 <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> 方法，并返回一个空的 <a class="reference internal" href="stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a> 。 <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.append()</span></code> 操作添加值到这个新的列表里。当键再次被存取时，就正常操作， <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.append()</span></code> 添加另一个值到列表中。这个计数比它的等价方法 <a class="reference internal" href="stdtypes.html#dict.setdefault" title="dict.setdefault"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.setdefault()</span></code></a> 要快速和简单:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">d</span><span class="o">.</span><span class="n">setdefault</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="p">[])</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">())</span>
<span class="go">[(&#39;blue&#39;, [2, 4]), (&#39;red&#39;, [1]), (&#39;yellow&#39;, [1, 3])]</span>
</pre></div>
</div>
<p>设置 <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> 为 <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> ，使 <a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> 在计数方面发挥好的作用（像其他语言中的bag或multiset）:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;mississippi&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">d</span><span class="p">[</span><span class="n">k</span><span class="p">]</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">())</span>
<span class="go">[(&#39;i&#39;, 4), (&#39;m&#39;, 1), (&#39;p&#39;, 2), (&#39;s&#39;, 4)]</span>
</pre></div>
</div>
<p>当一个字母首次遇到时，它就查询失败，所以 <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> 调用 <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> 来提供一个整数0作为默认值。自增操作然后建立对每个字母的计数。</p>
<p>函数 <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> 总是返回0，是常数函数的特殊情况。一个更快和灵活的方法是使用lambda函数，可以提供任何常量值(不只是0):</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">constant_factory</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="k">lambda</span><span class="p">:</span> <span class="n">value</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="n">constant_factory</span><span class="p">(</span><span class="s1">&#39;&lt;missing&gt;&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;John&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;ran&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">%(name)s</span><span class="s1"> </span><span class="si">%(action)s</span><span class="s1"> to </span><span class="si">%(object)s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">d</span>
<span class="go">&#39;John ran to &lt;missing&gt;&#39;</span>
</pre></div>
</div>
<p>设置 <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> 为 <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> 使 <a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> 用于构建字典集合:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">4</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="nb">set</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">d</span><span class="p">[</span><span class="n">k</span><span class="p">]</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">())</span>
<span class="go">[(&#39;blue&#39;, {2, 4}), (&#39;red&#39;, {1, 3})]</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="namedtuple-factory-function-for-tuples-with-named-fields">
<h2><a class="reference internal" href="#collections.namedtuple" title="collections.namedtuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">namedtuple()</span></code></a> 命名元组的工厂函数<a class="headerlink" href="#namedtuple-factory-function-for-tuples-with-named-fields" title="永久链接至标题">¶</a></h2>
<p>命名元组赋予每个位置一个含义，提供可读性和自文档性。它们可以用于任何普通元组，并添加了通过名字获取值的能力，通过索引值也是可以的。</p>
<dl class="function">
<dt id="collections.namedtuple">
<code class="sig-prename descclassname">collections.</code><code class="sig-name descname">namedtuple</code><span class="sig-paren">(</span><em class="sig-param">typename</em>, <em class="sig-param">field_names</em>, <em class="sig-param">*</em>, <em class="sig-param">rename=False</em>, <em class="sig-param">defaults=None</em>, <em class="sig-param">module=None</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.namedtuple" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个新的元组子类，名为 <em>typename</em> 。这个新的子类用于创建类元组的对象，可以通过域名来获取属性值，同样也可以通过索引和迭代获取值。子类实例同样有文档字符串（类名和域名）另外一个有用的 <a class="reference internal" href="../reference/datamodel.html#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a> 方法，以 <code class="docutils literal notranslate"><span class="pre">name=value</span></code> 格式列明了元组内容。</p>
<p><em>field_names</em> 是一个像 <code class="docutils literal notranslate"><span class="pre">[‘x’,</span> <span class="pre">‘y’]</span></code> 一样的字符串序列。另外 <em>field_names</em> 可以是一个纯字符串，用空白或逗号分隔开元素名，比如 <code class="docutils literal notranslate"><span class="pre">'x</span> <span class="pre">y'</span></code> 或者 <code class="docutils literal notranslate"><span class="pre">'x,</span> <span class="pre">y'</span></code> 。</p>
<p>任何有效的Python 标识符都可以作为域名，除了下划线开头的那些。有效标识符由字母，数字，下划线组成，但首字母不能是数字或下划线，另外不能是关键词 <a class="reference internal" href="keyword.html#module-keyword" title="keyword: Test whether a string is a keyword in Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">keyword</span></code></a> 比如 <em>class</em>, <em>for</em>, <em>return</em>, <em>global</em>, <em>pass</em>, 或 <em>raise</em> 。</p>
<p>如果 <em>rename</em> 为真， 无效域名会自动转换成位置名。比如 <code class="docutils literal notranslate"><span class="pre">['abc',</span> <span class="pre">'def',</span> <span class="pre">'ghi',</span> <span class="pre">'abc']</span></code> 转换成 <code class="docutils literal notranslate"><span class="pre">['abc',</span> <span class="pre">'_1',</span> <span class="pre">'ghi',</span> <span class="pre">'_3']</span></code> ， 消除关键词 <code class="docutils literal notranslate"><span class="pre">def</span></code>  和重复域名 <code class="docutils literal notranslate"><span class="pre">abc</span></code> 。</p>
<p><em>defaults</em> 可以为 <code class="docutils literal notranslate"><span class="pre">None</span></code> 或者是一个默认值的 <a class="reference internal" href="../glossary.html#term-iterable"><span class="xref std std-term">iterable</span></a> 。如果一个默认值域必须跟其他没有默认值的域在一起出现，<em>defaults</em> 就应用到最右边的参数。比如如果域名 <code class="docutils literal notranslate"><span class="pre">['x',</span> <span class="pre">'y',</span> <span class="pre">'z']</span></code> 和默认值 <code class="docutils literal notranslate"><span class="pre">(1,</span> <span class="pre">2)</span></code> ，那么 <code class="docutils literal notranslate"><span class="pre">x</span></code> 就必须指定一个参数值 ，<code class="docutils literal notranslate"><span class="pre">y</span></code> 默认值 <code class="docutils literal notranslate"><span class="pre">1</span></code> ， <code class="docutils literal notranslate"><span class="pre">z</span></code> 默认值 <code class="docutils literal notranslate"><span class="pre">2</span></code> 。</p>
<p>如果 <em>module</em> 值有定义，命名元组的 <code class="docutils literal notranslate"><span class="pre">__module__</span></code> 属性值就被设置。</p>
<p>命名元组实例没有字典，所以它们要更轻量，并且占用更小内存。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.1 版更改: </span>添加了对 <em>rename</em> 的支持。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.6 版更改: </span><em>verbose</em> 和 <em>rename</em> 参数成为 <a class="reference internal" href="../glossary.html#keyword-only-parameter"><span class="std std-ref">仅限关键字参数</span></a>.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.6 版更改: </span>添加了 <em>module</em> 参数。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>移去了 <em>verbose</em> 参数和属性 <code class="xref py py-attr docutils literal notranslate"><span class="pre">_source</span></code> 。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.7 版更改: </span>添加了 <em>defaults</em> 参数和 <code class="xref py py-attr docutils literal notranslate"><span class="pre">_field_defaults</span></code> 属性。</p>
</div>
</dd></dl>

<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Basic example</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Point</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Point&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">,</span> <span class="s1">&#39;y&#39;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">Point</span><span class="p">(</span><span class="mi">11</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="mi">22</span><span class="p">)</span>     <span class="c1"># instantiate with positional or keyword arguments</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">+</span> <span class="n">p</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>             <span class="c1"># indexable like the plain tuple (11, 22)</span>
<span class="go">33</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="n">p</span>                <span class="c1"># unpack like a regular tuple</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="p">,</span> <span class="n">y</span>
<span class="go">(11, 22)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">x</span> <span class="o">+</span> <span class="n">p</span><span class="o">.</span><span class="n">y</span>               <span class="c1"># fields also accessible by name</span>
<span class="go">33</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span>                       <span class="c1"># readable __repr__ with a name=value style</span>
<span class="go">Point(x=11, y=22)</span>
</pre></div>
</div>
<p>命名元组尤其有用于赋值 <a class="reference internal" href="csv.html#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a>  <a class="reference internal" href="sqlite3.html#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> 模块返回的元组</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">EmployeeRecord</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;EmployeeRecord&#39;</span><span class="p">,</span> <span class="s1">&#39;name, age, title, department, paygrade&#39;</span><span class="p">)</span>

<span class="kn">import</span> <span class="nn">csv</span>
<span class="k">for</span> <span class="n">emp</span> <span class="ow">in</span> <span class="nb">map</span><span class="p">(</span><span class="n">EmployeeRecord</span><span class="o">.</span><span class="n">_make</span><span class="p">,</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="s2">&quot;employees.csv&quot;</span><span class="p">,</span> <span class="s2">&quot;rb&quot;</span><span class="p">))):</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">emp</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">emp</span><span class="o">.</span><span class="n">title</span><span class="p">)</span>

<span class="kn">import</span> <span class="nn">sqlite3</span>
<span class="n">conn</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s1">&#39;/companydata&#39;</span><span class="p">)</span>
<span class="n">cursor</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;SELECT name, age, title, department, paygrade FROM employees&#39;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">emp</span> <span class="ow">in</span> <span class="nb">map</span><span class="p">(</span><span class="n">EmployeeRecord</span><span class="o">.</span><span class="n">_make</span><span class="p">,</span> <span class="n">cursor</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()):</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">emp</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">emp</span><span class="o">.</span><span class="n">title</span><span class="p">)</span>
</pre></div>
</div>
<p>除了继承元组的方法，命名元组还支持三个额外的方法和两个属性。为了防止域名冲突，方法和属性以下划线开始。</p>
<dl class="method">
<dt id="collections.somenamedtuple._make">
<em class="property">classmethod </em><code class="sig-prename descclassname">somenamedtuple.</code><code class="sig-name descname">_make</code><span class="sig-paren">(</span><em class="sig-param">iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.somenamedtuple._make" title="永久链接至目标">¶</a></dt>
<dd><p>类方法从存在的序列或迭代实例创建一个新实例。</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="p">[</span><span class="mi">11</span><span class="p">,</span> <span class="mi">22</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Point</span><span class="o">.</span><span class="n">_make</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
<span class="go">Point(x=11, y=22)</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.somenamedtuple._asdict">
<code class="sig-prename descclassname">somenamedtuple.</code><code class="sig-name descname">_asdict</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.somenamedtuple._asdict" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个新的 <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> ，它将字段名称映射到它们对应的值：</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">Point</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mi">11</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="mi">22</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">_asdict</span><span class="p">()</span>
<span class="go">OrderedDict([(&#39;x&#39;, 11), (&#39;y&#39;, 22)])</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.1 版更改: </span>返回一个 <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> 而不是  <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 。</p>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.somenamedtuple._replace">
<code class="sig-prename descclassname">somenamedtuple.</code><code class="sig-name descname">_replace</code><span class="sig-paren">(</span><em class="sig-param">**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.somenamedtuple._replace" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个新的命名元组实例，并将指定域替换为新的值</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">Point</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mi">11</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="mi">22</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mi">33</span><span class="p">)</span>
<span class="go">Point(x=33, y=22)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">partnum</span><span class="p">,</span> <span class="n">record</span> <span class="ow">in</span> <span class="n">inventory</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
<span class="gp">... </span>    <span class="n">inventory</span><span class="p">[</span><span class="n">partnum</span><span class="p">]</span> <span class="o">=</span> <span class="n">record</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">price</span><span class="o">=</span><span class="n">newprices</span><span class="p">[</span><span class="n">partnum</span><span class="p">],</span> <span class="n">timestamp</span><span class="o">=</span><span class="n">time</span><span class="o">.</span><span class="n">now</span><span class="p">())</span>
</pre></div>
</div>
</dd></dl>

<dl class="attribute">
<dt id="collections.somenamedtuple._fields">
<code class="sig-prename descclassname">somenamedtuple.</code><code class="sig-name descname">_fields</code><a class="headerlink" href="#collections.somenamedtuple._fields" title="永久链接至目标">¶</a></dt>
<dd><p>字符串元组列出了域名。用于提醒和从现有元组创建一个新的命名元组类型。</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">_fields</span>            <span class="c1"># view the field names</span>
<span class="go">(&#39;x&#39;, &#39;y&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Color</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Color&#39;</span><span class="p">,</span> <span class="s1">&#39;red green blue&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Pixel</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Pixel&#39;</span><span class="p">,</span> <span class="n">Point</span><span class="o">.</span><span class="n">_fields</span> <span class="o">+</span> <span class="n">Color</span><span class="o">.</span><span class="n">_fields</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Pixel</span><span class="p">(</span><span class="mi">11</span><span class="p">,</span> <span class="mi">22</span><span class="p">,</span> <span class="mi">128</span><span class="p">,</span> <span class="mi">255</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="go">Pixel(x=11, y=22, red=128, green=255, blue=0)</span>
</pre></div>
</div>
</dd></dl>

<dl class="attribute">
<dt id="collections.somenamedtuple._field_defaults">
<code class="sig-prename descclassname">somenamedtuple.</code><code class="sig-name descname">_field_defaults</code><a class="headerlink" href="#collections.somenamedtuple._field_defaults" title="永久链接至目标">¶</a></dt>
<dd><p>默认值的字典。</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Account</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Account&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;type&#39;</span><span class="p">,</span> <span class="s1">&#39;balance&#39;</span><span class="p">],</span> <span class="n">defaults</span><span class="o">=</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Account</span><span class="o">.</span><span class="n">_field_defaults</span>
<span class="go">{&#39;balance&#39;: 0}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Account</span><span class="p">(</span><span class="s1">&#39;premium&#39;</span><span class="p">)</span>
<span class="go">Account(type=&#39;premium&#39;, balance=0)</span>
</pre></div>
</div>
</dd></dl>

<p>要获取这个名字域的值，使用 <a class="reference internal" href="functions.html#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a> 函数 :</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">getattr</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="s1">&#39;x&#39;</span><span class="p">)</span>
<span class="go">11</span>
</pre></div>
</div>
<p>要将字典转换为命名元组，请使用 <code class="docutils literal notranslate"><span class="pre">**</span></code> 运算符（如 <a class="reference internal" href="../tutorial/controlflow.html#tut-unpacking-arguments"><span class="std std-ref">解包参数列表</span></a> 中所述）：</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;x&#39;</span><span class="p">:</span> <span class="mi">11</span><span class="p">,</span> <span class="s1">&#39;y&#39;</span><span class="p">:</span> <span class="mi">22</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Point</span><span class="p">(</span><span class="o">**</span><span class="n">d</span><span class="p">)</span>
<span class="go">Point(x=11, y=22)</span>
</pre></div>
</div>
<p>因为一个命名元组是一个正常的Python类，它可以很容易的通过子类更改功能。这里是如何添加一个计算域和定宽输出打印格式:</p>
<div class="highlight-pycon3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Point</span><span class="p">(</span><span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Point&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">,</span> <span class="s1">&#39;y&#39;</span><span class="p">])):</span>
<span class="gp">... </span>    <span class="vm">__slots__</span> <span class="o">=</span> <span class="p">()</span>
<span class="gp">... </span>    <span class="nd">@property</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">hypot</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">x</span> <span class="o">**</span> <span class="mi">2</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span> <span class="o">**</span> <span class="mi">2</span><span class="p">)</span> <span class="o">**</span> <span class="mf">0.5</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="fm">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="s1">&#39;Point: x=</span><span class="si">%6.3f</span><span class="s1">  y=</span><span class="si">%6.3f</span><span class="s1">  hypot=</span><span class="si">%6.3f</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">hypot</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">Point</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="n">Point</span><span class="p">(</span><span class="mi">14</span><span class="p">,</span> <span class="mi">5</span><span class="o">/</span><span class="mi">7</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="n">p</span><span class="p">)</span>
<span class="go">Point: x= 3.000  y= 4.000  hypot= 5.000</span>
<span class="go">Point: x=14.000  y= 0.714  hypot=14.018</span>
</pre></div>
</div>
<p>上面的子类设置 <code class="docutils literal notranslate"><span class="pre">__slots__</span></code> 为一个空元组。通过阻止创建实例字典保持了较低的内存开销。</p>
<p>子类化对于添加和存储新的名字域是无效的。应当通过 <a class="reference internal" href="#collections.somenamedtuple._fields" title="collections.somenamedtuple._fields"><code class="xref py py-attr docutils literal notranslate"><span class="pre">_fields</span></code></a> 创建一个新的命名元组来实现它:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Point3D</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Point3D&#39;</span><span class="p">,</span> <span class="n">Point</span><span class="o">.</span><span class="n">_fields</span> <span class="o">+</span> <span class="p">(</span><span class="s1">&#39;z&#39;</span><span class="p">,))</span>
</pre></div>
</div>
<p>文档字符串可以自定义，通过直接赋值给 <code class="docutils literal notranslate"><span class="pre">__doc__</span></code> 属性:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Book</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Book&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;id&#39;</span><span class="p">,</span> <span class="s1">&#39;title&#39;</span><span class="p">,</span> <span class="s1">&#39;authors&#39;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Book</span><span class="o">.</span><span class="vm">__doc__</span> <span class="o">+=</span> <span class="s1">&#39;: Hardcover book in active collection&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Book</span><span class="o">.</span><span class="n">id</span><span class="o">.</span><span class="vm">__doc__</span> <span class="o">=</span> <span class="s1">&#39;13-digit ISBN&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Book</span><span class="o">.</span><span class="n">title</span><span class="o">.</span><span class="vm">__doc__</span> <span class="o">=</span> <span class="s1">&#39;Title of first printing&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Book</span><span class="o">.</span><span class="n">authors</span><span class="o">.</span><span class="vm">__doc__</span> <span class="o">=</span> <span class="s1">&#39;List of authors sorted by last name&#39;</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span>文档字符串属性变成可写。</p>
</div>
<p>默认值可以用  <a class="reference internal" href="#collections.somenamedtuple._replace" title="collections.somenamedtuple._replace"><code class="xref py py-meth docutils literal notranslate"><span class="pre">_replace()</span></code></a> 来实现， 通过自定义一个原型实例:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Account</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Account&#39;</span><span class="p">,</span> <span class="s1">&#39;owner balance transaction_count&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">default_account</span> <span class="o">=</span> <span class="n">Account</span><span class="p">(</span><span class="s1">&#39;&lt;owner name&gt;&#39;</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">johns_account</span> <span class="o">=</span> <span class="n">default_account</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">owner</span><span class="o">=</span><span class="s1">&#39;John&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">janes_account</span> <span class="o">=</span> <span class="n">default_account</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">owner</span><span class="o">=</span><span class="s1">&#39;Jane&#39;</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="admonition-title">参见</p>
<ul>
<li><p>请参阅 <a class="reference internal" href="typing.html#typing.NamedTuple" title="typing.NamedTuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">typing.NamedTuple</span></code></a> ，以获取为命名元组添加类型提示的方法。 它还使用 <a class="reference internal" href="../reference/compound_stmts.html#class"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">class</span></code></a> 关键字提供了一种优雅的符号:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Component</span><span class="p">(</span><span class="n">NamedTuple</span><span class="p">):</span>
    <span class="n">part_number</span><span class="p">:</span> <span class="nb">int</span>
    <span class="n">weight</span><span class="p">:</span> <span class="nb">float</span>
    <span class="n">description</span><span class="p">:</span> <span class="n">Optional</span><span class="p">[</span><span class="nb">str</span><span class="p">]</span> <span class="o">=</span> <span class="kc">None</span>
</pre></div>
</div>
</li>
<li><p>对于以字典为底层的可变域名， 参考 <a class="reference internal" href="types.html#types.SimpleNamespace" title="types.SimpleNamespace"><code class="xref py py-meth docutils literal notranslate"><span class="pre">types.SimpleNamespace()</span></code></a> 。</p></li>
<li><p><a class="reference internal" href="dataclasses.html#module-dataclasses" title="dataclasses: Generate special methods on user-defined classes."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dataclasses</span></code></a> 模块提供了一个装饰器和一些函数，用于自动将生成的特殊方法添加到用户定义的类中。</p></li>
</ul>
</div>
</div>
<div class="section" id="ordereddict-objects">
<h2><a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> 对象<a class="headerlink" href="#ordereddict-objects" title="永久链接至标题">¶</a></h2>
<p>有序词典就像常规词典一样，但有一些与排序操作相关的额外功能。由于内置的 <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 类获得了记住插入顺序的能力（在 Python 3.7 中保证了这种新行为），它们变得不那么重要了。</p>
<p>一些与 <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 的不同仍然存在：</p>
<ul class="simple">
<li><p>常规的 <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 被设计为非常擅长映射操作。 跟踪插入顺序是次要的。</p></li>
<li><p><a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> 旨在擅长重新排序操作。 空间效率、迭代速度和更新操作的性能是次要的。</p></li>
<li><p>算法上， <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> 可以比 <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 更好地处理频繁的重新排序操作。 这使其适用于跟踪最近的访问（例如在 <a class="reference external" href="https://medium.com/&#64;krishankantsinghal/my-first-blog-on-medium-583159139237">LRU cache</a> 中）。</p></li>
<li><p>对于 <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> ，相等操作检查匹配顺序。</p></li>
<li><p><a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> 类的 <code class="xref py py-meth docutils literal notranslate"><span class="pre">popitem()</span></code> 方法有不同的签名。它接受一个可选参数来指定弹出哪个元素。</p></li>
<li><p><a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> 类有一个 <code class="xref py py-meth docutils literal notranslate"><span class="pre">move_to_end()</span></code> 方法，可以有效地将元素移动到任一端。</p></li>
<li><p>Python 3.8之前， <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 缺少 <a class="reference internal" href="../reference/datamodel.html#object.__reversed__" title="object.__reversed__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reversed__()</span></code></a> 方法。</p></li>
</ul>
<dl class="class">
<dt id="collections.OrderedDict">
<em class="property">class </em><code class="sig-prename descclassname">collections.</code><code class="sig-name descname">OrderedDict</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">items</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.OrderedDict" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个 <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 子类的实例，它具有专门用于重新排列字典顺序的方法。</p>
<div class="versionadded">
<p><span class="versionmodified added">3.1 新版功能.</span></p>
</div>
<dl class="method">
<dt id="collections.OrderedDict.popitem">
<code class="sig-name descname">popitem</code><span class="sig-paren">(</span><em class="sig-param">last=True</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.OrderedDict.popitem" title="永久链接至目标">¶</a></dt>
<dd><p>有序字典的 <a class="reference internal" href="#collections.OrderedDict.popitem" title="collections.OrderedDict.popitem"><code class="xref py py-meth docutils literal notranslate"><span class="pre">popitem()</span></code></a> 方法移除并返回一个 (key, value) 键值对。 如果 <em>last</em> 值为真，则按 <abbr title="last-in, first-out">LIFO</abbr> 后进先出的顺序返回键值对，否则就按 <abbr title="first-in, first-out">FIFO</abbr> 先进先出的顺序返回键值对。</p>
</dd></dl>

<dl class="method">
<dt id="collections.OrderedDict.move_to_end">
<code class="sig-name descname">move_to_end</code><span class="sig-paren">(</span><em class="sig-param">key</em>, <em class="sig-param">last=True</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.OrderedDict.move_to_end" title="永久链接至目标">¶</a></dt>
<dd><p>将现有 <em>key</em> 移动到有序字典的任一端。 如果 <em>last</em> 为真值（默认）则将元素移至末尾；如果  <em>last</em> 为假值则将元素移至开头。如果 <em>key</em> 不存在则会触发 <a class="reference internal" href="exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">OrderedDict</span><span class="o">.</span><span class="n">fromkeys</span><span class="p">(</span><span class="s1">&#39;abcde&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">move_to_end</span><span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span>
<span class="go">&#39;acdeb&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">move_to_end</span><span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="n">last</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span>
<span class="go">&#39;bacde&#39;</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified added">3.2 新版功能.</span></p>
</div>
</dd></dl>

</dd></dl>

<p>相对于通常的映射方法，有序字典还另外提供了逆序迭代的支持，通过 <a class="reference internal" href="functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a> 。</p>
<p><a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> 之间的相等测试是顺序敏感的，实现为 <code class="docutils literal notranslate"><span class="pre">list(od1.items())==list(od2.items())</span></code> 。 <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> 对象和其他的  <a class="reference internal" href="collections.abc.html#collections.abc.Mapping" title="collections.abc.Mapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mapping</span></code></a> 的相等测试，是顺序敏感的字典测试。这允许 <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> 替换为任何字典可以使用的场所。</p>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span><a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> 的项(item)，键(key)和值(value) <a class="reference internal" href="../glossary.html#term-dictionary-view"><span class="xref std std-term">视图</span></a> 现在支持逆序迭代，通过 <a class="reference internal" href="functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a> 。</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">在 3.6 版更改: </span><span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0468"><strong>PEP 468</strong></a> 赞成将关键词参数的顺序保留， 通过传递给 <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> 构造器和它的 <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code> 方法。</p>
</div>
<div class="section" id="ordereddict-examples-and-recipes">
<h3><a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> 例子和用法<a class="headerlink" href="#ordereddict-examples-and-recipes" title="永久链接至标题">¶</a></h3>
<p>创建记住键值 <em>最后</em> 插入顺序的有序字典变体很简单。 如果新条目覆盖现有条目，则原始插入位置将更改并移至末尾:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">LastUpdatedOrderedDict</span><span class="p">(</span><span class="n">OrderedDict</span><span class="p">):</span>
    <span class="s1">&#39;Store items in the order the keys were last added&#39;</span>

    <span class="k">def</span> <span class="fm">__setitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__setitem__</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
        <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">move_to_end</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
</pre></div>
</div>
<p>一个 <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> 对于实现 <a class="reference internal" href="functools.html#functools.lru_cache" title="functools.lru_cache"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.lru_cache()</span></code></a> 的变体也很有用:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">LRU</span><span class="p">(</span><span class="n">OrderedDict</span><span class="p">):</span>
    <span class="s1">&#39;Limit size, evicting the least recently looked-up key when full&#39;</span>

    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">maxsize</span><span class="o">=</span><span class="mi">128</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">maxsize</span> <span class="o">=</span> <span class="n">maxsize</span>
        <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">)</span>

    <span class="k">def</span> <span class="fm">__getitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
        <span class="n">value</span> <span class="o">=</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__getitem__</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">move_to_end</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">value</span>

    <span class="k">def</span> <span class="fm">__setitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__setitem__</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
        <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span> <span class="o">&gt;</span> <span class="bp">self</span><span class="o">.</span><span class="n">maxsize</span><span class="p">:</span>
            <span class="n">oldest</span> <span class="o">=</span> <span class="nb">next</span><span class="p">(</span><span class="nb">iter</span><span class="p">(</span><span class="bp">self</span><span class="p">))</span>
            <span class="k">del</span> <span class="bp">self</span><span class="p">[</span><span class="n">oldest</span><span class="p">]</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="userdict-objects">
<h2><a class="reference internal" href="#collections.UserDict" title="collections.UserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code></a> 对象<a class="headerlink" href="#userdict-objects" title="永久链接至标题">¶</a></h2>
<p><a class="reference internal" href="#collections.UserDict" title="collections.UserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code></a> 类是用作字典对象的外包装。对这个类的需求已部分由直接创建 <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 的子类的功能所替代；不过，这个类处理起来更容易，因为底层的字典可以作为属性来访问。</p>
<dl class="class">
<dt id="collections.UserDict">
<em class="property">class </em><code class="sig-prename descclassname">collections.</code><code class="sig-name descname">UserDict</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">initialdata</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.UserDict" title="永久链接至目标">¶</a></dt>
<dd><p>模拟一个字典类。这个实例的内容保存为一个正常字典， 可以通过 <a class="reference internal" href="#collections.UserDict" title="collections.UserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code></a> 实例的 <a class="reference internal" href="#collections.UserDict.data" title="collections.UserDict.data"><code class="xref py py-attr docutils literal notranslate"><span class="pre">data</span></code></a> 属性存取。如果提供了 <em>initialdata</em> 值， <a class="reference internal" href="#collections.UserDict.data" title="collections.UserDict.data"><code class="xref py py-attr docutils literal notranslate"><span class="pre">data</span></code></a> 就被初始化为它的内容；注意一个 <em>initialdata</em> 的引用不会被保留作为其他用途。</p>
<p><a class="reference internal" href="#collections.UserDict" title="collections.UserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code></a> 实例提供了以下属性作为扩展方法和操作的支持:</p>
<dl class="attribute">
<dt id="collections.UserDict.data">
<code class="sig-name descname">data</code><a class="headerlink" href="#collections.UserDict.data" title="永久链接至目标">¶</a></dt>
<dd><p>一个真实的字典，用于保存 <a class="reference internal" href="#collections.UserDict" title="collections.UserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code></a> 类的内容。</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="userlist-objects">
<h2><a class="reference internal" href="#collections.UserList" title="collections.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a> 对象<a class="headerlink" href="#userlist-objects" title="永久链接至标题">¶</a></h2>
<p>这个类封装了列表对象。它是一个有用的基础类，对于你想自定义的类似列表的类，可以继承和覆盖现有的方法，也可以添加新的方法。这样我们可以对列表添加新的行为。</p>
<p>对这个类的需求已部分由直接创建 <a class="reference internal" href="stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a> 的子类的功能所替代；不过，这个类处理起来更容易，因为底层的列表可以作为属性来访问。</p>
<dl class="class">
<dt id="collections.UserList">
<em class="property">class </em><code class="sig-prename descclassname">collections.</code><code class="sig-name descname">UserList</code><span class="sig-paren">(</span><span class="optional">[</span><em class="sig-param">list</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.UserList" title="永久链接至目标">¶</a></dt>
<dd><p>模拟一个列表。这个实例的内容被保存为一个正常列表，通过 <a class="reference internal" href="#collections.UserList" title="collections.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a> 的 <a class="reference internal" href="#collections.UserList.data" title="collections.UserList.data"><code class="xref py py-attr docutils literal notranslate"><span class="pre">data</span></code></a> 属性存取。实例内容被初始化为一个 <em>list</em> 的copy，默认为 <code class="docutils literal notranslate"><span class="pre">[]</span></code> 空列表。 <em>list</em> 可以是迭代对象，比如一个Python列表，或者一个  <a class="reference internal" href="#collections.UserList" title="collections.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a> 对象。</p>
<p><a class="reference internal" href="#collections.UserList" title="collections.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a> 提供了以下属性作为可变序列的方法和操作的扩展:</p>
<dl class="attribute">
<dt id="collections.UserList.data">
<code class="sig-name descname">data</code><a class="headerlink" href="#collections.UserList.data" title="永久链接至目标">¶</a></dt>
<dd><p>一个 <a class="reference internal" href="stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a> 对象用于存储 <a class="reference internal" href="#collections.UserList" title="collections.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a> 的内容。</p>
</dd></dl>

</dd></dl>

<p><strong>子类化的要求:</strong> <a class="reference internal" href="#collections.UserList" title="collections.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a> 的子类需要提供一个构造器，可以无参数调用，或者一个参数调用。返回一个新序列的列表操作需要创建一个实现类的实例。它假定了构造器可以以一个参数进行调用，这个参数是一个序列对象，作为数据源。</p>
<p>如果一个分离的类不希望依照这个需求，所有的特殊方法就必须重写；请参照源代码进行修改。</p>
</div>
<div class="section" id="userstring-objects">
<h2><a class="reference internal" href="#collections.UserString" title="collections.UserString"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code></a> 对象<a class="headerlink" href="#userstring-objects" title="永久链接至标题">¶</a></h2>
<p><a class="reference internal" href="#collections.UserString" title="collections.UserString"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code></a> 类是用作字符串对象的外包装。对这个类的需求已部分由直接创建 <a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> 的子类的功能所替代；不过，这个类处理起来更容易，因为底层的字符串可以作为属性来访问。</p>
<dl class="class">
<dt id="collections.UserString">
<em class="property">class </em><code class="sig-prename descclassname">collections.</code><code class="sig-name descname">UserString</code><span class="sig-paren">(</span><em class="sig-param">seq</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.UserString" title="永久链接至目标">¶</a></dt>
<dd><p>模拟一个字符串对象。这个实例对象的内容保存为一个正常字符串，通过 <a class="reference internal" href="#collections.UserString" title="collections.UserString"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code></a> 的 <a class="reference internal" href="#collections.UserString.data" title="collections.UserString.data"><code class="xref py py-attr docutils literal notranslate"><span class="pre">data</span></code></a> 属性存取。实例内容初始化设置为 <em>seq</em> 的copy。<em>seq</em> 参数可以是任何可通过内建 <a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> 函数转换为字符串的对象。</p>
<p><a class="reference internal" href="#collections.UserString" title="collections.UserString"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code></a> 提供了以下属性作为字符串方法和操作的额外支持：</p>
<dl class="attribute">
<dt id="collections.UserString.data">
<code class="sig-name descname">data</code><a class="headerlink" href="#collections.UserString.data" title="永久链接至目标">¶</a></dt>
<dd><p>一个真正的 <a class="reference internal" href="stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> 对象用来存放 <a class="reference internal" href="#collections.UserString" title="collections.UserString"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code></a> 类的内容。</p>
</dd></dl>

<div class="versionchanged">
<p><span class="versionmodified changed">在 3.5 版更改: </span>新方法 <code class="docutils literal notranslate"><span class="pre">__getnewargs__</span></code>, <code class="docutils literal notranslate"><span class="pre">__rmod__</span></code>, <code class="docutils literal notranslate"><span class="pre">casefold</span></code>, <code class="docutils literal notranslate"><span class="pre">format_map</span></code>, <code class="docutils literal notranslate"><span class="pre">isprintable</span></code>, 和 <code class="docutils literal notranslate"><span class="pre">maketrans</span></code>。</p>
</div>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">目录</a></h3>
  <ul>
<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code> --- 容器数据类型</a><ul>
<li><a class="reference internal" href="#chainmap-objects"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code> 对象</a><ul>
<li><a class="reference internal" href="#chainmap-examples-and-recipes"><code class="xref py py-class docutils literal notranslate"><span class="pre">ChainMap</span></code> 例子和方法</a></li>
</ul>
</li>
<li><a class="reference internal" href="#counter-objects"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code> 对象</a></li>
<li><a class="reference internal" href="#deque-objects"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code> 对象</a><ul>
<li><a class="reference internal" href="#deque-recipes"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code> 用法</a></li>
</ul>
</li>
<li><a class="reference internal" href="#defaultdict-objects"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code> 对象</a><ul>
<li><a class="reference internal" href="#defaultdict-examples"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code> 例子</a></li>
</ul>
</li>
<li><a class="reference internal" href="#namedtuple-factory-function-for-tuples-with-named-fields"><code class="xref py py-func docutils literal notranslate"><span class="pre">namedtuple()</span></code> 命名元组的工厂函数</a></li>
<li><a class="reference internal" href="#ordereddict-objects"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code> 对象</a><ul>
<li><a class="reference internal" href="#ordereddict-examples-and-recipes"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code> 例子和用法</a></li>
</ul>
</li>
<li><a class="reference internal" href="#userdict-objects"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code> 对象</a></li>
<li><a class="reference internal" href="#userlist-objects"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code> 对象</a></li>
<li><a class="reference internal" href="#userstring-objects"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code> 对象</a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="calendar.html"
                        title="上一章"><code class="xref py py-mod docutils literal notranslate"><span class="pre">calendar</span></code> --- 日历相关函数</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="collections.abc.html"
                        title="下一章"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections.abc</span></code> --- 容器的抽象基类</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">提交 Bug</a></li>
      <li>
        <a href="https://github.com/python/cpython/blob/3.7/Doc/library/collections.rst"
            rel="nofollow">显示源代码
        </a>
      </li>
    </ul>
  </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="总目录"
             >索引</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python 模块索引"
             >模块</a> |</li>
        <li class="right" >
          <a href="collections.abc.html" title="collections.abc --- 容器的抽象基类"
             >下一页</a> |</li>
        <li class="right" >
          <a href="calendar.html" title="calendar --- 日历相关函数"
             >上一页</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">3.7.8 Documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python 标准库</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" >数据类型</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="快速搜索" type="text" name="q" />
          <input type="submit" value="转向" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">版权所有</a> 2001-2020, Python Software Foundation.
    <br />
    Python 软件基金会是一个非盈利组织。
    <a href="https://www.python.org/psf/donations/">请捐助。</a>
    <br />
    最后更新于 6月 29, 2020.
    <a href="../bugs.html">发现了问题</a>？
    <br />
    使用<a href="http://sphinx.pocoo.org/">Sphinx</a>2.3.1 创建。
    </div>

  </body>
</html>